package com.hzeport.bgs22emduty.xxljob;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hzeport.bgs22emduty.config.SystemConfig;
import com.hzeport.bgs22emduty.dto.ApiResponseData;
import com.hzeport.bgs22emduty.entity.Appendix;
import com.hzeport.bgs22emduty.entity.ScreenDutyFile;
import com.hzeport.bgs22emduty.entity.ScreenDutyPlan;
import com.hzeport.bgs22emduty.enums.DeleteFlagEnum;
import com.hzeport.bgs22emduty.outbound.AppendixRepository;
import com.hzeport.bgs22emduty.outbound.ScreenDutyFileRepository;
import com.hzeport.bgs22emduty.outbound.ScreenDutyPlanRepository;
import com.hzeport.bgs22emduty.vo.FileDataVo;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * 定时拉取最新值班文件与预案文件
 */
@Slf4j
@Component
public class GetFileXxlJob {
    private static final ObjectMapper mapper = new ObjectMapper();
    @Resource
    private SystemConfig systemConfig;
    @Resource
    private ScreenDutyFileRepository screenDutyFileRepository;
    @Resource
    private AppendixRepository appendixRepository;
    @Resource
    private ScreenDutyPlanRepository screenDutyPlanRepository;

    @XxlJob("getFile")
    public ReturnT<String> getFileXxlJob(String param) throws JsonProcessingException {
        String tagCode = systemConfig.getTagCode();
        String[] split = tagCode.split(",");
        List<String> tagCodes = Arrays.asList(split);
        //查询数据库中当前生成时间最晚的一条
        List<Appendix> list = appendixRepository.lambdaQuery()
                .eq(Appendix::getSourceType,"1")
                .isNotNull(Appendix::getCreateTime)
                .orderByDesc(Appendix::getCreateTime).list();
        LocalDateTime startTime = null;
        if (!CollectionUtil.isEmpty(list)) {
            Appendix screenDutyFile = list.get(0);
            startTime = screenDutyFile.getCreateTime();
            startTime = startTime.plusMinutes(1);
        }else {
            startTime = LocalDateTime.now();
        }
        HashMap<String, Object> requestMap = new HashMap<>();
        requestMap.put("appId",systemConfig.getFileAppId());
        HashMap<String, Object> urlParams = new HashMap<>();
//        urlParams.put("text","");
        urlParams.put("updateTimeSort","DESC");
        urlParams.put("tagCode",tagCodes);
        urlParams.put("pageSize","100");
        requestMap.put("urlParams",urlParams);
        List<ScreenDutyFile> screenDutyFiles = new ArrayList<>();
        List<ScreenDutyPlan> screenDutyPlans = new ArrayList<>();
        List<Appendix> appendices = new ArrayList<>();
        int pageNumber = 1;
        while (true) {
            urlParams.put("pageNum",pageNumber);
            String string = mapper.writeValueAsString(requestMap);
            String body = HttpRequest.post(systemConfig.getFileUrl())
                    .header("Content-Type", "application/json")
                    .body(string)
                    .execute().body();
            ApiResponseData apiResponse = JSONUtil.toBean(body, ApiResponseData.class);
            if (!"200".equals(apiResponse.getCode())) {
                continue;
           }
            List<FileDataVo> data1 = apiResponse.getData().getResult();
           if (CollectionUtil.isEmpty(data1)) {
                break;
            }
            if (!CollectionUtil.isEmpty(list) ){
                for (FileDataVo fileDataVo : data1) {
                    if (startTime != null && fileDataVo.getCreatedTime().isAfter(startTime)){
                        String id = "";
                        //值班文件取配置第一个
                        if (fileDataVo.getZskTags().contains(tagCodes.get(0))){
                            ScreenDutyFile screenDutyFile = new ScreenDutyFile();
                            screenDutyFile.setTitle(fileDataVo.getTitle());
                            screenDutyFile.setCreateBy(fileDataVo.getCreatedUserName());
                            screenDutyFile.setCreateTime(fileDataVo.getCreatedTime());
//                screenDutyFile.setUpdateBy(fileDataVo.geti());
                            screenDutyFile.setUpdateTime(fileDataVo.getUpdateTime());
                            screenDutyFile.setDelFlag(DeleteFlagEnum.NOT_DELETE.getValue());
                            screenDutyFile.setId(fileDataVo.getId());
                            screenDutyFile.setCustomId(fileDataVo.getCustomCode());
                            screenDutyFile.setSourceType("1");
                            screenDutyFile.setCreatePerson(fileDataVo.getCreatedUserName());
//                screenDutyFile.setCustomId(fileDataVo.getCustomCode());
//                screenDutyFile.setCustomName(userInfoDetailVO.getCustomsName());
                            id = screenDutyFile.getId();
                            screenDutyFiles.add(screenDutyFile);
                        }
                        if (fileDataVo.getZskTags().contains(tagCodes.get(1))){
                            //应急预案取配置第2个
                            ScreenDutyPlan screenDutyFile = new ScreenDutyPlan();
                            screenDutyFile.setTitle(fileDataVo.getTitle());
                            screenDutyFile.setCreateBy(fileDataVo.getCreatedUserName());
                            screenDutyFile.setCreateTime(fileDataVo.getCreatedTime());
//                screenDutyFile.setUpdateBy(fileDataVo.geti());
                            screenDutyFile.setUpdateTime(fileDataVo.getUpdateTime());
                            screenDutyFile.setDelFlag(DeleteFlagEnum.NOT_DELETE.getValue());
                            screenDutyFile.setId(fileDataVo.getId());
                            screenDutyFile.setCustomId(fileDataVo.getCustomCode());
                            screenDutyFile.setSourceType("1");
                            screenDutyFile.setCreatePerson(fileDataVo.getCreatedUserName());
//                screenDutyFile.setCustomId(fileDataVo.getCustomCode());
//                screenDutyFile.setCustomName(userInfoDetailVO.getCustomsName());
                            id = screenDutyFile.getId();
                            screenDutyPlans.add(screenDutyFile);

                        }
                        Appendix appendix = new Appendix();
//                appendix.setSourceFileName(fileVO.getSourceFileName());
//                appendix.setCurrentFileName(fileVO.getCurrentFileName());
                        appendix.setFileUrl(fileDataVo.getUrl());
                        appendix.setCreateBy(fileDataVo.getCreatedUserName());
                        appendix.setCreateTime(LocalDateTime.now());
//                appendix.setUpdateBy(fileDataVo.getCreateTime());
                        appendix.setUpdateTime(fileDataVo.getUpdateTime());
                        appendix.setRelevanceId(id);
                        appendix.setDelFlag(DeleteFlagEnum.NOT_DELETE.getValue());
                        appendix.setSourceType("1");
                        appendices.add(appendix);



                    }
                }
            }else {
                String id = "";
                for (FileDataVo fileDataVo : data1) {
                    if (fileDataVo.getZskTags().contains(tagCodes.get(0))){
                        ScreenDutyFile screenDutyFile = new ScreenDutyFile();
                        screenDutyFile.setTitle(fileDataVo.getTitle());
                        screenDutyFile.setCreateBy(fileDataVo.getCreatedUserName());
                        screenDutyFile.setCreateTime(fileDataVo.getCreatedTime());
//                screenDutyFile.setUpdateBy(fileDataVo.geti());
                        screenDutyFile.setUpdateTime(fileDataVo.getUpdateTime());
                        screenDutyFile.setDelFlag(DeleteFlagEnum.NOT_DELETE.getValue());
                        screenDutyFile.setId(fileDataVo.getId());
                    screenDutyFile.setCustomId(fileDataVo.getCustomCode());
                    screenDutyFile.setSourceType("1");
                    screenDutyFile.setCreatePerson(fileDataVo.getCreatedUserName());
//                screenDutyFile.setCustomId(fileDataVo.getCustomCode());
//                screenDutyFile.setCustomName(userInfoDetailVO.getCustomsName());
                        id = screenDutyFile.getId();
                        screenDutyFiles.add(screenDutyFile);
                    }
                    if (fileDataVo.getZskTags().contains(tagCodes.get(1))){
                        //应急预案取配置第2个
                        ScreenDutyPlan screenDutyFile = new ScreenDutyPlan();
                        screenDutyFile.setTitle(fileDataVo.getTitle());
                        screenDutyFile.setCreateBy(fileDataVo.getCreatedUserName());
                        screenDutyFile.setCreateTime(fileDataVo.getCreatedTime());
//                screenDutyFile.setUpdateBy(fileDataVo.geti());
                        screenDutyFile.setUpdateTime(fileDataVo.getUpdateTime());
                        screenDutyFile.setDelFlag(DeleteFlagEnum.NOT_DELETE.getValue());
                        screenDutyFile.setId(fileDataVo.getId());
                        screenDutyFile.setCustomId(fileDataVo.getCustomCode());
                        screenDutyFile.setSourceType("1");
                        screenDutyFile.setCreatePerson(fileDataVo.getCreatedUserName());
//                screenDutyFile.setCustomId(fileDataVo.getCustomCode());
//                screenDutyFile.setCustomName(userInfoDetailVO.getCustomsName());
                        id = screenDutyFile.getId();
                        screenDutyPlans.add(screenDutyFile);
                    }

                        Appendix appendix = new Appendix();
//                appendix.setSourceFileName(fileVO.getSourceFileName());
//                appendix.setCurrentFileName(fileVO.getCurrentFileName());
                        appendix.setFileUrl(fileDataVo.getUrl());
                        appendix.setCreateBy(fileDataVo.getCreatedUserName());
                        appendix.setCreateTime(LocalDateTime.now());
//                appendix.setUpdateBy(fileDataVo.getCreateTime());
                        appendix.setUpdateTime(fileDataVo.getUpdateTime());
                        appendix.setRelevanceId(id);
                        appendix.setDelFlag(DeleteFlagEnum.NOT_DELETE.getValue());
                        appendix.setSourceType("1");
                        appendices.add(appendix);
                    }
            }
            pageNumber++;
        }
        screenDutyFileRepository.saveOrUpdateBatch(screenDutyFiles);
        appendixRepository.saveOrUpdateBatch(appendices);
        screenDutyPlanRepository.saveOrUpdateBatch(screenDutyPlans);
        return ReturnT.SUCCESS;
    }
}
